﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace theeg.DependencyAnalysis.CommonAddin.Models
{
    public static class Preferences
    {
        public static void Load(ISolution solution, IEnumerable<IProject> projects)
        {
            if (string.IsNullOrEmpty(solution.FileName))
            {
                return;
            }
            var fileInfo = new FileInfo(solution.FileName);
            string filename = fileInfo.Directory.FullName + "\\" + fileInfo.Name + ".dependency";
            if (!File.Exists(filename)) return;
            var projectList = projects.ToList();
            using (var stream = new FileStream(filename, FileMode.Open))
            {
                using (var reader = new StreamReader(stream))
                {
                    reader.ReadLine();
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        var separatorIndex = line.IndexOf(" = ", StringComparison.Ordinal);
                        if (separatorIndex < 0) continue;
                        var keyValue = line.Split(new[] { " = " }, StringSplitOptions.None);
                        bool isSelected;
                        bool.TryParse(keyValue[1], out isSelected);
                        var project = projectList.FirstOrDefault(x => x.Name == keyValue[0]);
                        if (project != null)
                        {
                            project.IsSelected = isSelected;
                        }
                    }
                }
            }
        }

        public static void Store(ISolution solution, IEnumerable<IProject> projects)
        {
            var fileInfo = new FileInfo(solution.FileName);
            string filename = fileInfo.Directory.FullName + "\\" + fileInfo.Name + ".dependency";
            using (var stream = new FileStream(filename, FileMode.OpenOrCreate))
            {
                using (var writer = new StreamWriter(stream))
                {
                    writer.WriteLine("[Projects]");
                    foreach (var project in projects)
                    {
                        writer.WriteLine(project.Name + " = " + project.IsSelected);
                    }
                }
            }
        }
    }
}
